package tool.test.mysql;

import com.alibaba.fastjson.JSONObject;
import top.codedance.iotp.common.util.SystemUtil;
import org.ini4j.Wini;
import tool.test.mysql.db.DBUtil;

import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Timer;
import java.util.TimerTask;

public class Runner {
    public static Wini ini = null; //ini文件读取器
    static long _period = 1000 * 30;//每 30秒执行一次
    final static String sql = "show variables like 'version'";

    public static void main(String[] args) {
        final SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Timer timer = new Timer();
        timer.schedule(new TimerTask() {
            public void run() {
                try {
                    Date createDate = new Date();
                    System.out.println("执行查询..." + formatter.format(createDate));
                    JSONObject jsonObject = new DBUtil().executeQuery(args.length > 0 ? args[0] : sql);
                    System.out.println(jsonObject.toJSONString());
                } catch (Exception ex) {
                    System.out.println(ex.getMessage());
                }
            }
        }, 0, _period);
    }

    /**
     * 读取ini配置文件
     */
    public static void initIniConfig() {
        String runtimeDirPath = SystemUtil.getRuntimeDirPath(Runner.class);
        String iniFilePath = runtimeDirPath + "init.ini";
        File f = new File(iniFilePath);
        if (f.exists()) {
            try {
                ini = new Wini(f);
            } catch (IOException e) {
                System.out.println("Ini file configure fail.");
            }
        } else {
            try {
                f.createNewFile();
                ini = new Wini(f);
            } catch (Exception e) {
                System.out.println("Create ini file fail.");
            }
        }
    }
}
